﻿using System;
using System.Collections.Generic;
using ZFramework.Runtime;

namespace ZGame
{
    public class EventSubscriber : IReference
    {
        private Dictionary<int, EventHandler<GameEventArgs>> dicEventHandler =
            new Dictionary<int, EventHandler<GameEventArgs>>();

        public object Owner { get; private set; }

        public EventSubscriber()
        {
            dicEventHandler = new Dictionary<int, EventHandler<GameEventArgs>>();
            Owner = null;
        }

        public void Subscribe(int id, EventHandler<GameEventArgs> handler)
        {
            if (handler == null)
            {
                Log.Error("Event handler is invalid.");
                return;
            }

            dicEventHandler.Add(id, handler);
            AOTGameEntry.eventMgr.Subscribe(id, handler);
        }

        public void UnSubscribe(int id, EventHandler<GameEventArgs> handler)
        {
            if (!dicEventHandler.ContainsKey(id))
            {
                Log.Error(Utility.Text.Format("Event '{0}' not exists specified handler.", id.ToString()));
                return;
            }

            AOTGameEntry.eventMgr.Unsubscribe(id, handler);
        }

        public void UnSubscribeAll()
        {
            if (dicEventHandler == null)
                return;

            foreach (var item in dicEventHandler)
            {
                var eventHandler = item.Value;
                AOTGameEntry.eventMgr.Unsubscribe(item.Key, eventHandler);
            }

            dicEventHandler.Clear();
        }

        public static EventSubscriber Create(object owner)
        {
            EventSubscriber eventSubscriber = ReferencePool.Acquire<EventSubscriber>();
            eventSubscriber.Owner = owner;

            return eventSubscriber;
        }

        public void Clear()
        {
            dicEventHandler.Clear();
            Owner = null;
        }
    }
}